# encoding=utf-8_general_ci

import os.path
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

from update import update

import torndb

from config import *

class QuestionsHandler(tornado.web.RequestHandler):
    def get(self):
        if not self.get_secure_cookie('user'):
            self.redirect("/login")
            return
        
        username = self.get_secure_cookie("user")

        try:
            db = torndb.Connection(db_host, db_name, user = db_user, password= db_password)
        except:
            return

        user_info = db.get("select * from user where username='"+username+"'")
        
        query = self.get_argument("query", "")

        if query == "":
            questions =  db.query("select * from problems")
            self.render("question.html", user = user_info, questions = questions)
            return
        
        try:
            question = db.get("select * from problems where pid='"+str(query)+"'")
        except:
            return

        try:
            comments = db.query("select * from discuss where pid='"+str(query)+"'")
        except:
            return

        self.render("question_detail.html", user = user_info, question = question, comments = comments)

    def post(self):
        pid = self.get_argument("pid", "")
        username = self.get_secure_cookie("user")
        code = self.get_argument("code", "")
        language = self.get_argument("language", "")

        if pid == "" or username == "" or code == "":
            return

        try:
            db = torndb.Connection(db_host, db_name, user = db_user, password= db_password)
        except:
            return

        user_info = db.get("select * from user where username='"+username+"'")
        question = db.get("select * from problems where pid='" + str(pid) + "'")
        user = db.get("select * from user where username='"+username+"'")
        code = code.replace("%", "%%")
        code = code.replace("\\", "\\\\")
        sql = "insert into status (pid, code, author, language) values ('" + str(pid) + "','" + code + "','" + username + "','"+ str(language) + "')";
        
        db.execute(sql)
        update()

